package cn.nawang.ebeim.client.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.nawang.ebeim.client.bean.BackStrategy;
import cn.nawang.ebeim.client.bean.BackupLog;
import cn.nawang.ebeim.client.bean.ClientConfiguration;
import cn.nawang.ebeim.client.bean.DataSource;
import cn.nawang.ebeim.client.bean.DataSourceVersion;
import cn.nawang.ebeim.client.bean.FileChangeLog;
import cn.nawang.ebeim.client.bean.HeartLog;
import cn.nawang.ebeim.client.bean.StorageCloud;
import cn.nawang.ebeim.client.bean.StorageServer;
import cn.nawang.ebeim.client.bean.TbStorageStrategy;
import cn.nawang.ebeim.client.exception.ApiRequestException;
import cn.nawang.ebeim.client.version.FileInfo;
import cn.nawang.ebeim.client.version.FileNode;
import cn.nawang.ebeim.client.version.Node;
import cn.nawang.ebeim.key.NaWangKey;

public class ApiUtil {
  private static final Logger LOG = LoggerFactory.getLogger(ApiUtil.class);
  public static final String OP_ADD = "add";
  public static final String OP_CHANGE = "change";
  public static final String OP_DELETE = "delete";
  public static final String OP_ERROR = "error";

  public static String getCriptKey() throws Exception {
    String customerId = PropertiesUtil.read(PropertiesConstants.CUSTOMER_ID);

    String key = ClientConfiguration.encriptKeyMap.get(customerId);
    if (key == null) {
      String dec2 = "";
      String userKey = "";
      dec2 = ApiVisitUtil.findCustomerEncryptionKeyByCustomerId(customerId);
      userKey = ApiVisitUtil.findCustomerKeyByCustomerId(customerId);
      key = NaWangKey.decryptKey(dec2, userKey);
      ClientConfiguration.encriptKeyMap.put(customerId, key);
    }
    return key;
  }



  /**
   * @author 张建峰
   * @Description: 更新数据源状态
   * @param @param dataSource
   * @param @param status
   * @return void
   * @throws ApiRequestException
   * @date 2015年8月21日下午5:22:47
   */
  public static void updateDataSourceStatus(DataSource dataSource, int status) {
    DataSource ds = new DataSource();
    ds.setId(dataSource.getId());
    ds.setStatus(status);
    ApiVisitUtil.updataDatasource(ds);
  }

  /**
   * @author 张建峰
   * @Description: 多条件查询backupLog
   * @param @param backupLog
   * @param @return
   * @return List<BackupLog>
   * @throws ApiRequestException
   * @date 2015年9月23日上午9:25:13
   *
   * @修改人 张建峰
   * @修改日期
   */
  public static List<BackupLog> getBackupLogList(BackupLog backupLog) throws ApiRequestException {
    List<BackupLog> list = null;
    list = ApiVisitUtil.getBackupLogList(backupLog);
    return list;
  }

  public static void addFileChangeLog(FileNode node, String dsId, String version)
      throws ApiRequestException {
    FileChangeLog log = new FileChangeLog();
    log.setDatasourceId(dsId);
    log.setOptype(getOpType(node.getStatus()));
    log.setVersion(version);
    log.setResult(String.valueOf(node.getStatus()));

    FileInfo info = node.getInfo();
    log.setSignature(info.getSignature());
    String fname = info.getPath() + File.separator + info.getName();
    log.setFileId(
        FileUtil.getFileId(PropertiesUtil.read(PropertiesConstants.CUSTOMER_ID), dsId, fname));
    int idx = info.getName().lastIndexOf(".");
    String suffix = "unknown";
    if (idx != -1) {
      suffix = info.getName().substring(idx);
    }
    log.setFileType(suffix);
    log.setFileSize(info.getFileSize());
    log.setLogTime(new Date().getTime());
    ApiVisitUtil.addFileChangeLog(log);
  }

  public static String getOpType(byte status) {
    if (status == Node.STATUS_ADD || status == Node.STATUS_NOOP) {
      return OP_ADD;
    } else if (status == Node.STATUS_CHANGE) {
      return OP_CHANGE;
    } else if (status == Node.STATUS_DELETED) {
      return OP_DELETE;
    }
    return OP_ERROR;
  }


  public static List<DataSource> getDataSources(String terminalId) throws ApiRequestException {
    List<DataSource> list = null;
    list = ApiVisitUtil.getDataSourceList(terminalId);
    return list;
  }


  public static void main(String[] args) throws Exception {
    ClientConfiguration.setCustomerId("33c8c253-a791-4a34-b3f3-90a66b73acea");
    ApiUtil.getCriptKey();
  }


  public static List<StorageServer> getStorageServers(StorageCloud sc) {
    LOG.debug("TODO - use server from database instead of the default one");
    List<StorageServer> ser = null;
    try {
      ser = ApiVisitUtil.getStorageCloudServerList(sc.getId());
    } catch (ApiRequestException e) {
      LOG.error("fali to getStorageCloudServerList", e);
      e.printStackTrace();
    }
    if (ser == null) {
      ser = new ArrayList<StorageServer>();
    }
    return ser;
  }

  // 没有用到
  public static List<StorageCloud> getStorageCloud(String customerId) throws ApiRequestException {
    LOG.debug("get storage cloud for this customer: {}", customerId);
    List<StorageCloud> list = null;
    list = ApiVisitUtil.getUserStorageCloudList(customerId);
    return list;
  }

  // public static Customer getCustomer(String terminalId) {
  // LOG.debug("get customer for terminal:{}", terminalId);
  // try {
  // return ApiVisitUtil.getCustomerByTerminalId(terminalId);
  // } catch (Exception e) {
  // LOG.error("failed to get customer by terminalId:{}", terminalId, e);
  // }
  // return null;
  // }

  public static DataSource getDataSource(String dsId) {
    LOG.debug("TODO - get datasource by dsId:{}", dsId);
    DataSource ds = null;
    try {
      ds = ApiVisitUtil.getDataSource(dsId);
    } catch (ApiRequestException e) {
      LOG.error("fali to getDataSource", e);
      e.printStackTrace();
    }
    return ds;
  }

  public static String addBackupLog(BackupLog backupLog) {
    String result = "false";
    try {
      result = ApiVisitUtil.addBackupLog(backupLog);
    } catch (ApiRequestException e) {
      LOG.error("failed to addBackupLog: {}", e);
      e.printStackTrace();
    }
    return result;
  }

  public static String updataBackupLog(BackupLog backupLog) throws ApiRequestException {
    String result = "false";
    result = ApiVisitUtil.updateBackupLog(backupLog);
    return result;
  }

  /**
   * @author 张建峰
   * @Description: TODO
   * @param @param dataSource
   * @param @param nextVersion
   * @return void
   * @throws ApiRequestException
   * @date 2015年8月21日下午5:22:14
   *
   * @修改人 张建峰
   * @修改日期
   */
  public static void updateDataSourceVersion(DataSource dataSource, DataSourceVersion nextVersion)
      throws ApiRequestException {
    DataSource ds = new DataSource();
    ds.setId(dataSource.getId());
    ds.setCurrentVersionMajor(nextVersion.getMajorVersion());
    ds.setCurrentVersionMinor(nextVersion.getMinorVersion());
    ApiVisitUtil.updataDatasource(ds);
  }

  /**
   * @author 张建峰
   * @Description: 根据数据源Id获取备份策略
   * @param @param dsId
   * @param @return
   * @return BackStrategy
   * @throws ApiRequestException
   * @date 2015年8月25日上午8:30:29
   *
   * @修改人 张建峰
   * @修改日期
   */
  public static BackStrategy getBackStrategyByDsId(String dsId) throws ApiRequestException {
    BackStrategy bs = null;
    bs = ApiVisitUtil.getBackStrategyByDatasourceId(dsId);
    return bs;
  }

  /**
   * @author 张建峰
   * @Description: 根据id更新backupTimeStatus状态
   * @param @param id BackStrategy的唯一标示
   * @param @param backupTimeStatus 针对backupTime是否更新过的状态
   * @return void
   * @throws ApiRequestException
   * @date 2015年8月26日下午4:38:05
   *
   * @修改人 张建峰
   * @修改日期
   */
  public static void updateBackStrategyStatus(String id, int backupTimeStatus)
      throws ApiRequestException {
    BackStrategy bs = new BackStrategy();
    bs.setBsId(id);
    bs.setBackupTimeStatus(backupTimeStatus);
    ApiVisitUtil.updataBackStrategy(bs);
  }

  public static void deleteBackupLog(BackupLog backupLog) {
    try {
      ApiVisitUtil.deleteBackupLog(backupLog);
    } catch (ApiRequestException e) {
      // TODO Auto-generated catch block
      LOG.error("fail to deleteBackupLog: {}", e);
      e.printStackTrace();
    }
  }

  public static void deleteFileChangeLogs(String dsId) throws ApiRequestException {
    ApiVisitUtil.deleteFileChangeLog(dsId);
  }

  public static List<TbStorageStrategy> findCloudIdByCustomerId(String customerId)
      throws ApiRequestException {
    LOG.info("findCloudIdByCustomerId--------------------:customerId:" + customerId);
    List<TbStorageStrategy> list = null;
    list = ApiVisitUtil.getTbStorageStrategyByCustomerId(customerId);
    return list;
  }

  public static String addHeartLog(HeartLog heartLog) throws ApiRequestException {
    String rs = null;
    rs = ApiVisitUtil.addHeartLog(heartLog);
    return rs;
  }


}
